package cn.iocoder.yudao.module.eval.controller.admin.statistics;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.module.eval.controller.admin.statistics.vo.*;
import cn.iocoder.yudao.module.eval.service.statistics.EvalStatisticsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

@Tag(name = "管理后台 - 统计分析")
@RestController
@RequestMapping("/eval/statistics")
@Validated
@Slf4j
public class EvalStatisticsController {

    @Resource
    private EvalStatisticsService statisticsService;

    // ==================== 企业统计 ====================

    @GetMapping("/enterprise/overview")
    @Operation(summary = "企业评价概览")
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalEnterpriseOverviewRespVO> getEnterpriseOverview() {
        EvalEnterpriseOverviewRespVO overview = statisticsService.getEnterpriseOverview();
        return success(overview);
    }

    @GetMapping("/enterprise/plans")
    @Operation(summary = "企业计划统计")
    @Parameter(name = "startDate", description = "开始日期", required = false)
    @Parameter(name = "endDate", description = "结束日期", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalEnterprisePlanStatisticsRespVO> getEnterprisePlanStatistics(
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        EvalEnterprisePlanStatisticsRespVO statistics = statisticsService.getEnterprisePlanStatistics(startDate, endDate);
        return success(statistics);
    }

    @GetMapping("/enterprise/candidates")
    @Operation(summary = "企业参评人员统计")
    @Parameter(name = "startDate", description = "开始日期", required = false)
    @Parameter(name = "endDate", description = "结束日期", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalEnterpriseCandidateStatisticsRespVO> getEnterpriseCandidateStatistics(
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        EvalEnterpriseCandidateStatisticsRespVO statistics = statisticsService.getEnterpriseCandidateStatistics(startDate, endDate);
        return success(statistics);
    }

    @GetMapping("/enterprise/professions")
    @Operation(summary = "企业职业覆盖统计")
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalEnterpriseProfessionCoverageRespVO> getEnterpriseProfessionCoverage() {
        EvalEnterpriseProfessionCoverageRespVO coverage = statisticsService.getEnterpriseProfessionCoverage();
        return success(coverage);
    }

    @GetMapping("/enterprise/evaluators")
    @Operation(summary = "企业考评员统计")
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalEnterpriseEvaluatorStatisticsRespVO> getEnterpriseEvaluatorStatistics() {
        EvalEnterpriseEvaluatorStatisticsRespVO statistics = statisticsService.getEnterpriseEvaluatorStatistics();
        return success(statistics);
    }

    @GetMapping("/enterprise/training-effectiveness")
    @Operation(summary = "培训效果统计")
    @Parameter(name = "startDate", description = "开始日期", required = false)
    @Parameter(name = "endDate", description = "结束日期", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalTrainingEffectivenessRespVO> getTrainingEffectiveness(
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        EvalTrainingEffectivenessRespVO effectiveness = statisticsService.getTrainingEffectiveness(startDate, endDate);
        return success(effectiveness);
    }

    @GetMapping("/enterprise/monthly-trend")
    @Operation(summary = "企业月度趋势统计")
    @Parameter(name = "year", description = "年份", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<List<EvalEnterpriseMonthlyTrendRespVO>> getEnterpriseMonthlyTrend(
            @RequestParam(value = "year", required = false) Integer year) {
        List<EvalEnterpriseMonthlyTrendRespVO> trend = statisticsService.getEnterpriseMonthlyTrend(year);
        return success(trend);
    }

    // ==================== 监管统计 ====================

    @GetMapping("/supervision/overview")
    @Operation(summary = "跨企业数据总览（监管员）")
    @PreAuthorize("@ss.hasPermission('eval:statistics:supervision')")
    public CommonResult<EvalSupervisionOverviewRespVO> getSupervisionOverview() {
        EvalSupervisionOverviewRespVO overview = statisticsService.getSupervisionOverview();
        return success(overview);
    }

    @GetMapping("/supervision/enterprise-activities")
    @Operation(summary = "企业评价活动统计")
    @Parameter(name = "enterpriseId", description = "企业ID", required = false)
    @Parameter(name = "startDate", description = "开始日期", required = false)
    @Parameter(name = "endDate", description = "结束日期", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:supervision')")
    public CommonResult<List<EvalEnterpriseActivityStatisticsRespVO>> getEnterpriseActivityStatistics(
            @RequestParam(value = "enterpriseId", required = false) Long enterpriseId,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        List<EvalEnterpriseActivityStatisticsRespVO> statistics = statisticsService.getEnterpriseActivityStatistics(enterpriseId, startDate, endDate);
        return success(statistics);
    }

    @GetMapping("/supervision/profession-distribution")
    @Operation(summary = "职业分布统计")
    @Parameter(name = "region", description = "地区", required = false)
    @Parameter(name = "industry", description = "行业", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:supervision')")
    public CommonResult<List<EvalProfessionDistributionRespVO>> getProfessionDistribution(
            @RequestParam(value = "region", required = false) String region,
            @RequestParam(value = "industry", required = false) String industry) {
        List<EvalProfessionDistributionRespVO> distribution = statisticsService.getProfessionDistribution(region, industry);
        return success(distribution);
    }

    @GetMapping("/supervision/quality-analysis")
    @Operation(summary = "评价质量分析")
    @Parameter(name = "startDate", description = "开始日期", required = false)
    @Parameter(name = "endDate", description = "结束日期", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:supervision')")
    public CommonResult<EvalQualityAnalysisRespVO> getQualityAnalysis(
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        EvalQualityAnalysisRespVO analysis = statisticsService.getQualityAnalysis(startDate, endDate);
        return success(analysis);
    }

    @GetMapping("/supervision/regional-comparison")
    @Operation(summary = "区域对比分析")
    @Parameter(name = "regions", description = "对比地区", required = false)
    @Parameter(name = "year", description = "年份", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:supervision')")
    public CommonResult<List<EvalRegionalComparisonRespVO>> getRegionalComparison(
            @RequestParam(value = "regions", required = false) String regions,
            @RequestParam(value = "year", required = false) Integer year) {
        List<EvalRegionalComparisonRespVO> comparison = statisticsService.getRegionalComparison(regions, year);
        return success(comparison);
    }

    // ==================== 专项统计 ====================

    @GetMapping("/plan/{planId}/detailed")
    @Operation(summary = "计划详细统计")
    @Parameter(name = "planId", description = "计划ID", required = true)
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalPlanDetailedStatisticsRespVO> getPlanDetailedStatistics(@PathVariable("planId") Long planId) {
        EvalPlanDetailedStatisticsRespVO statistics = statisticsService.getPlanDetailedStatistics(planId);
        return success(statistics);
    }

    @GetMapping("/profession/{professionCode}/analysis")
    @Operation(summary = "职业评价分析")
    @Parameter(name = "professionCode", description = "职业代码", required = true)
    @Parameter(name = "startDate", description = "开始日期", required = false)
    @Parameter(name = "endDate", description = "结束日期", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalProfessionAnalysisRespVO> getProfessionAnalysis(
            @PathVariable("professionCode") String professionCode,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        EvalProfessionAnalysisRespVO analysis = statisticsService.getProfessionAnalysis(professionCode, startDate, endDate);
        return success(analysis);
    }

    @GetMapping("/evaluator/{evaluatorId}/performance")
    @Operation(summary = "考评员绩效分析")
    @Parameter(name = "evaluatorId", description = "考评员ID", required = true)
    @Parameter(name = "startDate", description = "开始日期", required = false)
    @Parameter(name = "endDate", description = "结束日期", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalEvaluatorPerformanceRespVO> getEvaluatorPerformance(
            @PathVariable("evaluatorId") Long evaluatorId,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        EvalEvaluatorPerformanceRespVO performance = statisticsService.getEvaluatorPerformance(evaluatorId, startDate, endDate);
        return success(performance);
    }

    // ==================== 报表导出 ====================

    @GetMapping("/export/enterprise-report")
    @Operation(summary = "导出企业统计报表")
    @Parameter(name = "reportType", description = "报表类型", required = true)
    @Parameter(name = "startDate", description = "开始日期", required = false)
    @Parameter(name = "endDate", description = "结束日期", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportEnterpriseReport(@RequestParam("reportType") String reportType,
                                      @RequestParam(value = "startDate", required = false) String startDate,
                                      @RequestParam(value = "endDate", required = false) String endDate,
                                      HttpServletResponse response) throws IOException {
        statisticsService.exportEnterpriseReport(reportType, startDate, endDate, response);
    }

    @GetMapping("/export/supervision-report")
    @Operation(summary = "导出监管统计报表")
    @Parameter(name = "reportType", description = "报表类型", required = true)
    @Parameter(name = "region", description = "地区", required = false)
    @Parameter(name = "startDate", description = "开始日期", required = false)
    @Parameter(name = "endDate", description = "结束日期", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:supervision')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportSupervisionReport(@RequestParam("reportType") String reportType,
                                       @RequestParam(value = "region", required = false) String region,
                                       @RequestParam(value = "startDate", required = false) String startDate,
                                       @RequestParam(value = "endDate", required = false) String endDate,
                                       HttpServletResponse response) throws IOException {
        statisticsService.exportSupervisionReport(reportType, region, startDate, endDate, response);
    }

    // ==================== 自定义统计 ====================

    @PostMapping("/custom-query")
    @Operation(summary = "自定义统计查询")
    @PreAuthorize("@ss.hasPermission('eval:statistics:custom')")
    public CommonResult<EvalCustomStatisticsRespVO> customStatisticsQuery(@Valid @RequestBody EvalCustomStatisticsReqVO queryReqVO) {
        EvalCustomStatisticsRespVO result = statisticsService.customStatisticsQuery(queryReqVO);
        return success(result);
    }

    @GetMapping("/dashboard/widgets")
    @Operation(summary = "获取仪表盘组件数据")
    @Parameter(name = "widgetTypes", description = "组件类型列表", required = false)
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<List<EvalDashboardWidgetRespVO>> getDashboardWidgets(
            @RequestParam(value = "widgetTypes", required = false) String widgetTypes) {
        List<EvalDashboardWidgetRespVO> widgets = statisticsService.getDashboardWidgets(widgetTypes);
        return success(widgets);
    }

    @GetMapping("/real-time/metrics")
    @Operation(summary = "获取实时指标")
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalRealTimeMetricsRespVO> getRealTimeMetrics() {
        EvalRealTimeMetricsRespVO metrics = statisticsService.getRealTimeMetrics();
        return success(metrics);
    }

    // ==================== 数据对比 ====================

    @PostMapping("/compare/periods")
    @Operation(summary = "时期对比分析")
    @PreAuthorize("@ss.hasPermission('eval:statistics:query')")
    public CommonResult<EvalPeriodComparisonRespVO> comparePeriods(@Valid @RequestBody EvalPeriodComparisonReqVO comparisonReqVO) {
        EvalPeriodComparisonRespVO comparison = statisticsService.comparePeriods(comparisonReqVO);
        return success(comparison);
    }

    @PostMapping("/compare/enterprises")
    @Operation(summary = "企业对比分析")
    @PreAuthorize("@ss.hasPermission('eval:statistics:supervision')")
    public CommonResult<EvalEnterpriseComparisonRespVO> compareEnterprises(@Valid @RequestBody EvalEnterpriseComparisonReqVO comparisonReqVO) {
        EvalEnterpriseComparisonRespVO comparison = statisticsService.compareEnterprises(comparisonReqVO);
        return success(comparison);
    }

}
